package com.zkca.xf.ui.activity.personprotect;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.compress.CompressImage;
import com.jph.takephoto.compress.CompressImageImpl;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.MyApplication;
import com.zkca.xf.R;
import com.zkca.xf.base.BaseTitleActivity;
import com.zkca.xf.model.javabean.DeviceType;
import com.zkca.xf.model.javabean.uploadbean.RequestInspect;
import com.zkca.xf.presenter.DeviceAddPresenter;
import com.zkca.xf.ui.adapter.SingleAdapter;
import com.zkca.xf.ui.adapter.ViewHolder;
import com.zkca.xf.ui.customview.FilterImageView;
import com.zkca.xf.utils.AppUtils;
import com.zkca.xf.utils.DisplayUtil;
import com.zkca.xf.utils.LogUtil;
import com.zkca.xf.utils.PopWindowUtil;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.utils.SpaceItemDecoration;
import com.zkca.xf.utils.TimeUtils;
import com.zkca.xf.utils.ToastUtils;
import com.zkca.xf.view.DeviceAddView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class DeviceaddAct extends BaseTitleActivity implements DeviceAddView, View.OnClickListener, TakePhoto.TakeResultListener, InvokeListener {

    @BindView(R.id.header_bar_photo_back)
    ImageView headerBarPhotoBack;
    @BindView(R.id.header_bar_photo_delete)
    ImageView headerBarPhotoDelete;
    @BindView(R.id.bigimage)
    ImageView bigimage;
    @BindView(R.id.ll_bigimage)
    LinearLayout llBigimage;

    @BindView(R.id.etID)
    TextView etID;
    @BindView(R.id.line_shebeiID)
    LinearLayout lineShebeiID;


    @BindView(R.id.line_shebeileixing)
    LinearLayout lineShebeileixing;


    @BindView(R.id.etName_)
    EditText etName;
    @BindView(R.id.line_shebeimingc)
    LinearLayout lineShebeimingc;

    @BindView(R.id.etSite)
    EditText etSite;
    @BindView(R.id.line_shebeididian)
    LinearLayout lineShebeididian;

    @BindView(R.id.post_add_pic)
    FilterImageView postAddPic;
    @BindView(R.id.post_pic_container)
    LinearLayout postPicContainer;
    @BindView(R.id.post_scrollview)
    HorizontalScrollView postScrollview;
    @BindView(R.id.line_shebeitupian)
    LinearLayout lineShebeitupian;


    @BindView(R.id.relativeLayout_one)
    RelativeLayout relativeLayoutOne;

    @BindView(R.id.BaoCun)
    Button baoCun;
    @BindView(R.id.type_text)
    TextView typeText;
    @BindView(R.id.leixing)
    LinearLayout leixing;


    private RelativeLayout adddevice;
    private View pop_phone;
    private TextView tv_photo_cancel, tv_photo_album, tv_photograph;

    private String userId;
    private PopupWindow popupDevicetype;


    private List<DeviceType.DataBean> devicTypelist = new ArrayList();
    private InvokeParam invokeParam;
    private Uri imageUri;//压缩后图片保存路径
    private TakePhoto takePhoto;
    private File file;
    private List<File> imageFiles = new ArrayList<>();//需要上传的文件集合
    private final int MAXNUM = 3;//最多上传图片数
    //被放大的那张图的file，也是可能会被删的图片
    private File tempFile;
    //被放大的图在picContainer中的位置
    private int index;
    private RequestBody imageBody;


    private DeviceAddPresenter xunDianAddPresenter;
    private RequestInspect requestInspect;

    private Map upDatamap = new HashMap();//设备上传的map
    private String deviseid;
    private String image1, image2, image3, deviceTypeid, deviceName, deviceAdss, deviceImages;
    private List<String> picNames = new ArrayList<>();
    SingleAdapter<DeviceType.DataBean> adapter;

    private CompressConfig compressConfig;
    ArrayList<TImage> images;

    private Dialog loadingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_a);
        ButterKnife.bind(this);
        initmView();
        checkDevice();
        initPop_phone();
        initTypePop();
        initDvaddData();
        xunDianAddPresenter = new DeviceAddPresenter(this, this);
        xunDianAddPresenter.getDvType(requestInspect);

    }

    private void initDvaddData() {
        requestInspect = new RequestInspect();
        Map map = new HashMap<String, Object>();
        map.put("devId", deviseid);
        requestInspect.setParam(map);
        requestInspect.setAccessId(SPUtil.getString(this, Constants_SP.ACCESSID));
        requestInspect.setAction(0);
        requestInspect.setTimeStamp(TimeUtils.getTime());
        requestInspect.setSign(MyApplication.getInstance().generateDvSign(requestInspect));
    }

    private void initPop_phone() {
        adddevice = findViewById(R.id.adddevice);
        pop_phone = LayoutInflater.from(this).inflate(R.layout.pop_head, null, false);
        tv_photo_cancel = (TextView) pop_phone.findViewById(R.id.tv_photo_cancel);
        tv_photo_album = (TextView) pop_phone.findViewById(R.id.tv_photo_album);
        tv_photograph = (TextView) pop_phone.findViewById(R.id.tv_photograph);
        tv_photo_cancel.setOnClickListener(this);
        tv_photo_album.setOnClickListener(this);
        tv_photograph.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leixing:
                popupDevicetype.showAsDropDown(leixing, 0, 20);
                break;
            case R.id.post_add_pic://头像
                PopWindowUtil.showPopWindow(this, pop_phone, adddevice);
                break;
            case R.id.tv_photo_cancel:
                PopWindowUtil.popupWindow.dismiss();
                break;
            case R.id.tv_photo_album://从相册

                PopWindowUtil.popupWindow.dismiss();
                takePhoto = getTakePhoto();
                configCompress(takePhoto);
                int maxNum = MAXNUM - imageFiles.size();
                takePhoto.onPickMultipleWithCrop(maxNum, getCropOptions());
                break;
            case R.id.tv_photograph://拍照
                file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists())
                    file.getParentFile().mkdirs();
                imageUri = Uri.fromFile(file);
                PopWindowUtil.popupWindow.dismiss();
                takePhoto = getTakePhoto();
                configCompress(takePhoto);
                takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
                break;
            case R.id.BaoCun:

                initUpdata();
                break;
            case R.id.header_bar_photo_back:
                llBigimage.setVisibility(View.GONE);
                setTitleBarVisibility(true);
                relativeLayoutOne.setVisibility(View.VISIBLE);
                break;
            case R.id.header_bar_photo_delete:
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提示")
                        .setMessage("要删除这张照片吗?")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                builder.create().dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                //从集合中移除该图片
                                imageFiles.remove(index);
                                if (imageFiles.size() >= MAXNUM) {
                                    postAddPic.setVisibility(View.GONE);
                                } else {
                                    postAddPic.setVisibility(View.VISIBLE);
                                }
                                //从容器中移除该图片
                                postPicContainer.removeView(postPicContainer.getChildAt(index));
                                llBigimage.setVisibility(View.GONE);
                                setTitleBarVisibility(true);
                                relativeLayoutOne.setVisibility(View.VISIBLE);
                            }
                        }).show();
                break;
            default:
                if (view instanceof ImageView) {
                    tempFile = (File) view.getTag();
                    //获取被放大的图在picContainer中的位置
                    index = postPicContainer.indexOfChild(view);
                    //显示大图
                    llBigimage.setVisibility(View.VISIBLE);
                    relativeLayoutOne.setVisibility(View.GONE);
                    setTitleBarVisibility(false);
                    Drawable drawable = ((ImageView) view).getDrawable();
                    bigimage.setImageDrawable(drawable);

                    //进场动画
                }
                break;
        }
    }


    public static String convertIconToString(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();// 转为byte数组
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }


    /**
     * 裁剪
     *
     * @return
     */
    private CropOptions getCropOptions() {
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setOutputX(1000).setOutputY(1000);//裁剪框宽高
        builder.setWithOwnCrop(true);
        return builder.create();
    }


    /**
     * 压缩
     *
     * @param takePhoto
     */
    private void configCompress(TakePhoto takePhoto) {
        CompressConfig config;

        config = new CompressConfig.Builder().setMaxSize(500 * 1024).setMaxPixel(800).create();

        takePhoto.onEnableCompress(config, true);
    }

    private void initUpdata() {
        if (imageFiles.size() == 0) {
            ToastUtils.show(this, "请添加至少一张图片");
        } else if (TextUtils.isEmpty(etSite.getText().toString())) {
            ToastUtils.show(this, "请添加设备地点");
        } else if (TextUtils.isEmpty(etName.getText().toString())) {
            ToastUtils.show(this, "请添加设备名称");
        } else if (typeText.getText().equals("请选择")) {
            ToastUtils.show(this, "请选择设备类型");
        } else {
            loadingDialog.show();
            baoCun.setClickable(false);
            for (int i = 0; i < imageFiles.size(); i++) {
                File file = imageFiles.get(i);
                String absolutePath = file.getAbsolutePath();
                Bitmap bitmap = BitmapFactory.decodeFile(absolutePath);
                String s = convertIconToString(bitmap);
                if (i == 0) {
                    image1 = s;
                } else if (i == 1) {
                    image2 = s;
                } else if (i == 2) {
                    image3 = s;
                }
                LogUtil.e("121", "大小：" + file.length() + "B    " + file.length() / 1024 + "Kb");
            }
            deviceAdss = etSite.getText().toString();
            deviceName = etName.getText().toString();

            requestInspect = new RequestInspect();
            Map map = new HashMap<String, Object>();
            map.put("devId", deviseid);
            map.put("devName", deviceName);
            map.put("devType", deviceTypeid);
            map.put("installPosition", deviceAdss);
            map.put("devImage1", image1);
            if (image3 != null) {
                map.put("devImage3", image3);
            }
            if (image2 != null) {
                map.put("devImage2", image2);
            }
            requestInspect.setParam(map);
            requestInspect.setAccessId(SPUtil.getString(this, Constants_SP.ACCESSID));
            requestInspect.setAction(1);
            requestInspect.setTimeStamp(TimeUtils.getTime());
            requestInspect.setSign(MyApplication.getInstance().generateDvSign(requestInspect));
            xunDianAddPresenter.addDevice(requestInspect);
        }
    }

    private void checkDevice() {
        Map<String, String> map = new HashMap<>();
        map.put("id", deviseid);
        map.put("s5", "3");
    }

    private void initTypePop() {

        View popupView = getLayoutInflater().inflate(R.layout.poplist, null);
        popupDevicetype = new PopupWindow(popupView, AppUtils.dip2px(this, 300), ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupDevicetype.setTouchable(true);
        popupDevicetype.setOutsideTouchable(true);
        popupDevicetype.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));

        XRecyclerView recyclerView = popupView.findViewById(R.id.devicetype_list);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new SpaceItemDecoration(DisplayUtil.dip2px(
                mContext, 0.5f)));
        adapter = new SingleAdapter<DeviceType.DataBean>(mContext, devicTypelist, R.layout.item_text) {

            @Override
            public void convert(ViewHolder holder, final DeviceType.DataBean dataBean, int position) {
                final String typeName = dataBean.getTypeName();
                TextView textView = holder.getView(R.id.item_text);
                textView.setText(typeName);
                holder.setItemViewOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        typeText.setText(typeName);
                        typeText.setTextColor(Color.rgb(102, 102, 102));
                        popupDevicetype.dismiss();
                        deviceTypeid = dataBean.getTypeId();
                    }
                });
            }
        };

        recyclerView.setAdapter(adapter);

        leixing.setOnClickListener(this);
    }

    private void initmView() {
        setTitleText("巡点添加");
        setleftTextVisibility(true);
        setleftImgVisibility(true);

        loadingDialog=new Dialog(mContext);
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView     = inflater.inflate(R.layout.dialogloading, null);
        //将自定义布局设置进去
        loadingDialog.setContentView(dialogView);
        loadingDialog.setCanceledOnTouchOutside(false);

        Intent intent = getIntent();
        deviseid = intent.getStringExtra("ID");
        etID.setText(deviseid);

        userId = SPUtil.getString(this, Constants_SP.USER_ID, "");

        postAddPic.setOnClickListener(this);
        baoCun.setOnClickListener(this);
        headerBarPhotoBack.setOnClickListener(this);//大图退出
        headerBarPhotoDelete.setOnClickListener(this);//图片删除

        compressConfig = new CompressConfig.Builder().setMaxSize(500 * 1024).setMaxPixel(800).create();

    }


    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }


    @Override
    public void takeSuccess(TResult result) {
        images = result.getImages();

        //图片的布局参数
        int size = (int) getResources().getDimension(R.dimen.size_110);
        int padding = (int) getResources().getDimension(R.dimen.padding_10);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size, size);
        params.rightMargin = padding;
        TImage tImage = images.get(0);


        for (int i = 0; i < images.size(); i++) {
            String compressPath = images.get(i).getOriginalPath();
            ImageView iv = new ImageView(this);
            iv.setLayoutParams(params);
            iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Glide.with(this).load(compressPath).into(iv);

            File file = new File(compressPath);
            //给每个imageview设置一个File的Tag，方便在删除的时候用
            iv.setTag(file);
            iv.setOnClickListener(this);
            imageFiles.add(file);

            if (imageFiles.size() >= MAXNUM) {
                postAddPic.setVisibility(View.GONE);
            }
            postPicContainer.addView(iv, postPicContainer.getChildCount() - 1);

        }
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void showProgressDialog() {
       // showSpinKitLoading(true);
        LogUtil.e("此处展示进度条", "34567");
    }

    @Override
    public void hideProgressDialog() {
      //  showSpinKitLoading(false);
        LogUtil.e("此处隐藏进度条", "34567");
    }

    @Override
    public void showError(String msg) {
        ToastUtils.show(mContext, "请求失败，失败原因："+msg);
        loadingDialog.dismiss();
        finish();
    }

    @Override
    public void getDvtype(DeviceType deviceType) {
        LogUtil.e("设备验证通过", deviceType.getInfo());
        if (deviceType.getResult() == 0) {
            List<DeviceType.DataBean> data = deviceType.getData();
            devicTypelist.addAll(data);
            adapter.notifyDataSetChanged();
        } else if (deviceType.getResult() == 9) {
            ToastUtils.show(this, deviseid + "设备已添加！");
            finish();
        }
    }

    @Override
    public void inPut(String s) {
        ToastUtils.show(mContext, "设备上传成功");
        loadingDialog.dismiss();
        finish();
    }

}
